<template>
  <div class="wrap">
    <a-spin :spinning="spinning">
      <a-drawer
        :title="title"
        placement="right"
        :closable="true"
        :visible="visible"
        :headerStyle="{ 'padding-top': '20px' }"
        width="495px"
        :after-visible-change="afterVisibleChange"
        zIndex="2"
        @close="onClose"
      >
        <div id="components-form-demo-vuex">
          <a-form-model
            ref="ruleForm"
            :model="form"
            :rules="rules"
            layout="vertical"
          >
            <a-form-model-item ref="name" label="名称" prop="name">
              <a-input v-model="form.name" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item ref="mobile" label="手机号" prop="mobile">
              <a-input v-model="form.mobile" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="部门" prop="parentDepartmentName">
              <a-input
                v-model="form.parentDepartmentName"
                readOnly
                placeholder="点击选择部门"
                @click="showModal"
              />
            </a-form-model-item>
            <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button type="primary" @click="onSubmit"> 确 定 </a-button>
              <a-button
                style="margin-left: 10px"
                @click="resetForm"
                v-show="addOrUpdate == 0"
              >
                重 置
              </a-button>
            </a-form-model-item>
          </a-form-model>
          <div>
            <a-modal
              v-model="modelVisible"
              title="部门列表"
              on-ok="handleOk"
              @cancel="noMoelSelect"
            >
              <template slot="footer">
                <a-button key="back" @click="handleCancel"> 取消 </a-button>
                <a-button
                  key="submit"
                  type="primary"
                  :loading="loading"
                  @click="handleOk"
                >
                  确定
                </a-button>
              </template>
              <a-tree
                style="
                  min-width: 170px !important;
                  margin-top: 10px;
                  max-height: 400px;
                  overflow-y: auto;
                "
                :tree-data="nodeData"
                :autoExpandParent="true"
                :defaultExpandParent="true"
                :replace-fields="replaceFields"
                :defaultExpandedKeys="[nodeData[0].depId]"
                show-icon
                @select="selectDept"
              >
              </a-tree>
            </a-modal>
          </div>
        </div>
      </a-drawer>

      <a-drawer
        :title="title"
        placement="right"
        :closable="true"
        :visible="visible2"
        :headerStyle="{ 'padding-top': '20px' }"
        width="495px"
        :after-visible-change="afterVisibleChange"
        zIndex="2"
        @close="onClose"
      >
        <div id="components-form-demo-vuex">
          <a-form-model
            ref="ruleForm2"
            :model="form2"
            :rules="rules2"
            layout="vertical"
          >
            <a-form-model-item ref="name" label="部门名称" prop="name">
              <a-input v-model="form2.name" placeholder="请输入" />
            </a-form-model-item>

            <a-form-model-item label="上级部门" prop="parentDepartmentName">
              <a-input
                v-model="form2.parentDepartmentName"
                readOnly
                placeholder="点击选择部门"
                @click="showModal"
              />
            </a-form-model-item>
            <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button type="primary" @click="onSubmit2"> 确 定 </a-button>
              <a-button
                style="margin-left: 10px"
                @click="resetForm2"
                v-show="addOrUpdate == 0"
              >
                重 置
              </a-button>
            </a-form-model-item>
          </a-form-model>
          <div>
            <a-modal
              v-model="modelVisible"
              title="部门列表"
              on-ok="handleOk"
              @cancel="noMoelSelect"
            >
              <template slot="footer">
                <a-button key="back" @click="handleCancel"> 取消 </a-button>
                <a-button
                  key="submit"
                  type="primary"
                  :loading="loading"
                  @click="handleOk"
                >
                  确定
                </a-button>
              </template>
              <a-tree
                style="
                  min-width: 170px !important;
                  margin-top: 10px;
                  max-height: 400px;
                  overflow-y: auto;
                "
                :tree-data="nodeData"
                :autoExpandParent="true"
                :defaultExpandParent="true"
                :replace-fields="replaceFields"
                :defaultExpandedKeys="[nodeData[0].depId]"
                show-icon
                @select="selectDept"
              >
              </a-tree>
            </a-modal>
          </div>
        </div>
      </a-drawer>
      <a-row style="background: #fff; border-radius: 6px">
        <a-col :span="6" style="overflow-y: auto;padding: 10px;">
          <a-input-search style="width: 250px;" placeholder="请输入搜索的部门"  allow-clear />
          <a-tree
            style="
              min-width: 170px !important;
              height: calc(100vh - 260px);
            "
            :tree-data="nodeData"
            :autoExpandParent="true"
            :defaultExpandParent="true"
            defaultExpandAll
            :defaultExpandedKeys="[nodeData[0].depId]"
            show-icon
            @select="onSelect"
          >
            <template #title="{ name, depId }">
              <a-dropdown :trigger="['contextmenu']">
                <span>{{ name }}</span>
                <template #overlay>
                  <a-menu
                    @click="
                      ({ key: menuKey }) => onContextMenuClick(depId, menuKey)
                    "
                  >
                    <a-menu-item key="1">编辑</a-menu-item>
                    <a-menu-item key="2">删除</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
          </a-tree>
        </a-col>

        <a-col
          :span="18"
          style="
            padding: 10px;
            border-left: 4px solid #edeff2;
            min-height: calc(100vh - 200px);
          "
        >
          <div style="margin-top: 10px">
            <div>
              <span style="color: #171a1d; font-weight: 600; font-size: 17px">{{
                deptName
              }}</span>
            </div>
            <div style="margin-top: 15px" class="set_font_set">
              <a-button type="primary" @click="addDept2">
                <a-icon type="user-add" />创建部门
              </a-button>
              <a-button
                type="primary"
                @click="addDept"
                style="margin-left: 20px"
              >
                <a-icon type="user-add" />添加用户
              </a-button>

              <a-button
                type="primary"
                @click="clearDara"
                style="margin-left: 20px"
              >
                <a-icon type="setting" />清除缓存
              </a-button>
            </div>
          </div>
          <a-table
            rowKey="id"
            :loading="loading"
            style="margin-top: 15px"
            :columns="columns"
            :data-source="reslist"
            bordered
          >
            <span slot="avatar" slot-scope="avatar">
              <img :src="avatar" style="width: 40px; height: 40px" />
            </span>
          </a-table>
        </a-col>
      </a-row>
    </a-spin>
  </div>
</template>

<script>
const columns = [
  {
    title: "userid",
    dataIndex: "userid",
  },
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "手机号",
    dataIndex: "mobile",
  },
  {
    title: "头像",
    dataIndex: "avatar",
    scopedSlots: { customRender: "avatar" },
  },
];

const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`,
  });
}

// 数组对象中查找符合目标的对象
const parseArray = function (objArray, key, value) {
  for (let i in objArray) {
    let element = objArray[i];
    if (typeof element === "object") {
      let result = parseArray(element, key, value);
      if (result) return result;
    } else {
      if (i === key) {
        if (element === value) return objArray;
      }
    }
  }
};

import contacts from "@/api/organizations";
import cmeduGateway from "@/api/cmeduGateway";
export default {
  name: "index1",
  data() {
    this.cacheData = data.map((item) => ({ ...item }));
    return {
      form: {
        dept_id_list: "",
        parentDepartmentName: "",
        name: "",
        mobile: "",
      },
      form2: {
        parent_id: "",
        parentDepartmentName: "",
        name: "",
      },
      data,
      columns,
      editingKey: "",
      deptName: "",
      loading: false,
      userInfo: [],
      visible: false,
      visible2: false,
      spinning: true,
      addOrUpdate: 0,
      modelVisible: false,
      getById: "",
      replaceFields: {
        title: "name",
        key: "depId",
        child: "children",
      },
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        //mobile
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
        ],
        parentDepartmentName: [
          { required: true, message: "部门不能为空", trigger: "change" },
        ],
      },
      rules2: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        parentDepartmentName: [
          { required: true, message: "部门不能为空", trigger: "change" },
        ],
      },
      nodeData: [{}],
      deptId: "",
      codeLine: "",
      selectedKeys: null,
      filterResource: null,
      reslist: [],
    };
  },
  async created() {
    // 树的获取
    this.getInit();

    // this.treeOnLoad = false;
  },
  mounted() {},
  methods: {
    async clearDara() {
      let res = await contacts.removeCache();
      if (res.data == "ok") {
        this.$message.success("清除缓存成功,请刷新页面");
      }
    },

    addDept2() {
      this.visible2 = true;
    },
    onContextMenuClick(treeKey, menuKey) {
      switch (menuKey) {
        case "1": //编辑
          break;
        case "2": //删除
          this.showDeleteConfirm(treeKey);
          break;
      }
    },
    showDeleteConfirm(obj) {
      let that = this;
      this.$confirm({
        title: "您确定要删除这条数据吗",
        content: "此操作可能有风险",
        okText: "确定",
        okType: "danger",
        cancelText: "否",
        onOk() {
          contacts.delOrg(obj).then((res) => {
            if (res.data == "删除成功") {
              that.$message.success("删除成功");
              that.getInit();
            }
          });
        },
        onCancel() {},
      });
    },
    editDept(obj) {
      this.addOrUpdate = 1;
      (this.deptId = obj.id),
        (this.form.department = obj.orgName),
        (this.form.parentDepartmentId = obj.parentId),
        (this.form.parentDepartmentName = obj.parentName);
      this.visible = true;
    },
    resetForm() {
      (this.form = {
        parentDepartmentId: "",
        parentDepartmentName: "",
        department: "",
      }),
        this.$refs.ruleForm.resetFields();
    },
    resetForm2() {
      (this.form2 = {
        parent_id: "",
        parentDepartmentName: "",
        name: "",
      }),
        this.$refs.ruleForm2.resetFields();
    },
    selectDept(params, e) {
      this.form.parentDepartmentName = e.node._props.title;
      this.form.dept_id_list = params[0];

      this.form2.parentDepartmentName = e.node._props.title;
      this.form2.parent_id = params[0];
    },
    async onSelect(params, e) {
      this.loading = true;
      this.deptName = e.selectedNodes[0].data.props.name;
      let depId = e.selectedNodes[0].data.props.depId;
      let data = {
        cursor: 0,
        contain_access_limit: false,
        size: 10,
        order_field: "modify_desc",
        language: "zh_CN",
        dept_id: depId,
      };
      let res = await cmeduGateway.getUserData(data);

      if (res.data.errcode == 0) {
        this.reslist = res.data.result.list;
      }
      this.loading = false;
    },
    async getInit() {
      let data = {
        token: "",
        deptId: 1,
      };
      let res = await contacts.getDingTree(data);
      let arr = [];
      arr.push(res.data);
      this.nodeData = arr;
      this.spinning = false;
      this.deptName = res.data.name;
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let organization = {
            name: this.form.name,
            mobile: this.form.mobile,
            dept_id_list: this.form.dept_id_list.toString(),
          };
          if (this.addOrUpdate == 0) {
            cmeduGateway.createUser(organization).then((res) => {
              // if (res.errcode == 0) {
              this.$message.success(res.data.errmsg);
              // this.getInit();
              this.visible = false;
              // }
            });
          }
          if (this.addOrUpdate == 1) {
            organization.id = this.deptId;
            contacts.updateOrg(organization).then((res) => {
              if (res.data == "修改成功") {
                this.$message.success("修改成功");
                this.getInit();
                this.visible = false;
              }
            });
          }
        } else {
          return false;
        }
      });
    },

    onSubmit2() {
      this.$refs.ruleForm2.validate((valid) => {
        if (valid) {
          let organization = {
            name: this.form2.name,
            parent_id: this.form2.parent_id.toString(),
          };
          if (this.addOrUpdate == 0) {
            cmeduGateway.createDepartment(organization).then((res) => {
              // if (res.errcode == 0) {
              if (res.data.errmsg == "ok") {
                this.$message.success("创建部门成功，请点击清除缓存并刷新页面");
              }

              // this.getInit();
              this.visible2 = false;
              // }
            });
          }
          if (this.addOrUpdate == 1) {
            organization.id = this.deptId;
            contacts.updateOrg(organization).then((res) => {
              if (res.data == "修改成功") {
                this.$message.success("修改成功");
                this.getInit();
                this.visible = false;
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    handleOk() {
      this.modelVisible = false;
    },
    noMoelSelect() {
      this.form.parentDepartmentName = "";
      this.form.parentDepartmentId = "";
    },
    handleCancel(e) {
      this.form.parentDepartmentName = "";
      this.form.parentDepartmentId = "";
      this.modelVisible = false;
    },
    onClose() {
      this.form = {
        parentDepartmentId: "",
        parentDepartmentName: "",
        department: "",
      };
      this.addOrUpdate = 0;
      (this.deptId = ""), (this.visible = false);
      this.visible2 = false
    },
    showModal() {
      this.modelVisible = true;
    },
    showDrawer() {
      this.visible = true;
    },
    addDept() {
      this.title = "添加子部门";
      this.showDrawer();
    },
    // 获取全部节点树
    async GetLimsConfigNode() {
      // this.nodeData = await GetLimsConfigNodeData();
    },
    // 新增、修改节点操作，此处为打开新增修改界面，调用实际后端接口进行节点的处理操作
    async nodeHandle() {},
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    save(key) {
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.find((item) => key === item.key);
      const targetCache = newCacheData.find((item) => key === item.key);
      if (target && targetCache) {
        delete target.editable;
        this.data = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = "";
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => key === item.key)
        );
        delete target.editable;
        this.data = newData;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.wrap {
  position: relative;
}

.set_button_margin_left {
  margin-left: 15px;
}
</style>

<style lang="less">
.set_font_size {
  font-size: 14px !important;
}
</style>
<style lang="less">
.ant-drawer-title {
  margin: 0;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  font-size: 14px;
  line-height: 22px;
}

.set_drawer_div {
  margin-top: -15px;
  width: 490px;
  height: 48px;
  font-weight: 500;
  color: #171a1d;
  font-size: 14px;
}
</style>
